import { WebRTCClient } from './class/webrtc-client';

document.addEventListener('DOMContentLoaded', () => {
    const startBtn = document.getElementById('startBtn');
    const remoteVideo = document.getElementById('remoteVideo') as HTMLVideoElement;
    const localVideo = document.getElementById('localVideo') as HTMLVideoElement;

    var webrtc = new WebRTCClient('ws://10.5.141.1:3000');

    webrtc.onLocalStreamReady = (stream) => {
        console.log("onLocalStreamReady called");
        console.log("Stream object:", stream);
        console.log("Stream active:", stream.active);
        console.log("Video tracks:", stream.getVideoTracks());

        if (localVideo) {
            console.log("Setting stream to localVideo element");
            localVideo.srcObject = stream;
            localVideo.play().then(() => {
                console.log("Local video play successful");
            }).catch(err => {
                console.error("Failed to play local video:", err);
            });
            localVideo.onloadedmetadata = () => {
                console.log("Local video metadata loaded");
                console.log(`Video dimensions: ${localVideo.videoWidth}x${localVideo.videoHeight}`);
            };

            localVideo.onplaying = () => {
                console.log("Local video started playing");
            };

            localVideo.onerror = (e) => {
                console.error("Local video error:", e);
            };

            localVideo.play().catch(err => {
                console.error("Failed to play local video:", err);
            });
        }
    };
    localVideo.onloadedmetadata = () => {
        console.log("Local video metadata loaded");
    };

    webrtc.onRemoteStreamReady = (stream) => {
        console.log("Remote stream info:", {
            active: stream.active,
            videoTracks: stream.getVideoTracks().length,
            audioTracks: stream.getAudioTracks().length
        });
        
        stream.getTracks().forEach(track => {
            console.log("Remote track:", {
                kind: track.kind,
                readyState: track.readyState,
                muted: track.muted
            });
        });
        
        remoteVideo.srcObject = stream;
    };

    startBtn?.addEventListener('click', () => {
        webrtc.start("default");
    });
});